import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { User } from '../../auth/entities/user.entity';

/**
 * 消息类型
 */
export enum MessageType {
  TEXT = 'text', // 文本消息
  IMAGE = 'image', // 图片消息
  VIDEO = 'video', // 视频消息
  AUDIO = 'audio', // 语音消息
  FILE = 'file', // 文件消息
}

/**
 * 私信消息实体
 */
@Entity('messages')
@Index(['senderId', 'receiverId']) // 优化查询
@Index(['conversationId', 'createdAt']) // 优化会话消息查询
export class Message {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ comment: '会话ID（由较小的userId和较大的userId组合生成）' })
  @Index()
  conversationId: string;

  @Column({ comment: '发送者ID' })
  senderId: number;

  @Column({ comment: '接收者ID' })
  receiverId: number;

  @Column({
    type: 'enum',
    enum: MessageType,
    default: MessageType.TEXT,
    comment: '消息类型',
  })
  type: MessageType;

  @Column({ type: 'text', comment: '消息内容' })
  content: string;

  @Column({
    type: 'text',
    nullable: true,
    comment: '媒体文件URL（图片、视频、音频等）',
  })
  mediaUrl: string | null;

  @Column({ default: false, comment: '是否已读' })
  isRead: boolean;

  @Column({ type: 'timestamp', nullable: true, comment: '已读时间' })
  readAt: Date | null;

  @Column({ default: false, comment: '是否已删除（发送者删除）' })
  isDeletedBySender: boolean;

  @Column({ default: false, comment: '是否已删除（接收者删除）' })
  isDeletedByReceiver: boolean;

  @ManyToOne(() => User, { eager: true, onDelete: 'CASCADE' })
  @JoinColumn({ name: 'senderId' })
  sender: User;

  @ManyToOne(() => User, { eager: true, onDelete: 'CASCADE' })
  @JoinColumn({ name: 'receiverId' })
  receiver: User;

  @CreateDateColumn({ type: 'timestamp', comment: '创建时间' })
  createdAt: Date;

  @UpdateDateColumn({ type: 'timestamp', comment: '更新时间' })
  updatedAt: Date;
}
